#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;

#define cilent_type 1
#define servers_type 2
#define Size 1024

const char *pathname = "/home/ryan/Linux_code/linux/35_msg_cli_ser";
const int proj_id = 0x11223344;

struct my_msgbuf
{
    long mtype;             /* message type, must be > 0 */
    char mtext[Size] = {0}; /* message data */
};

key_t getftok()
{
    key_t key = ftok(pathname, proj_id);
    if (key < 0)
    {
        cerr << "ftok error! eoorr:" << errno << " strerror:" << strerror(errno) << endl;
        exit(1);
    }
    return key;
}

int get_msqid(key_t key)
{
    int msqid = msgget(key, IPC_CREAT | 0666);
    if (msqid < 0)
    {
        cerr << "get_msqid error! eoorr:" << errno << " strerror:" << strerror(errno) << endl;
        exit(1);
    }
    return msqid;
}

int send_msg(int msqid, int m_type, char *in)
{
    struct my_msgbuf buf;
    buf.mtype = m_type;
    strncpy(buf.mtext, in, sizeof in);
    int n = msgsnd(msqid, (void *)&buf, sizeof buf.mtext, 0);
    if (n < 0)
    {
        cerr << "msg_send error! eoorr:" << errno << " strerror:" << strerror(errno) << endl;
        exit(1);
    }
    return 1;
}

int recive_msg(int msqid, int m_type, char *out)
{
    struct my_msgbuf buf;
    int n = msgrcv(msqid, (void *)&buf, sizeof buf.mtext,m_type,0);
    if (n < 0)
    {
        cerr << "msg_recive error! eoorr:" << errno << " strerror:" << strerror(errno) << endl;
        exit(1);
    }
    strncpy(out,buf.mtext,sizeof out);
    return 1;
}

int realse_msg(int msgid)
{
    int n = msgctl(msgid, IPC_RMID, nullptr);
    if (n < 0)
    {
        cerr << "realse_msqid error! eoorr:" << errno << " strerror:" << strerror(errno) << endl;
        exit(1);
    }
    return 1;
}